import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routers'
import ViewUI from 'view-design'
import access from '@/utils/access.js'
import store from '@/store'
import ErrorCode from '@/libs/errorCode'
import IgnoreAccess from '@/libs/ignoreAccess'
import {getStoreByJson} from '@/utils/storeUtil'

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

const router = new VueRouter({
  routes
})

/**
 * 异常处理
 */
const errorHandle = status => {
  ViewUI.Notice.error({
    title: ErrorCode[status]
  })
}

/**
 * 获取菜单访问权限
 */
const getAccess = () =>{
  let accessStore = getStoreByJson('access')
  if(accessStore){
    return [...access,...accessStore]
  }else{
    return access
  }
}

router.beforeEach((to, from, next) => {
  console.log(from)
  // 加载进度条
  ViewUI.LoadingBar.start()
  /**
   * 权限验证规则：
   * 1、判断是否登录页面，是登录页面放行
   * 2、判断是否登录，没有登录跳转登录页面
   * 3、判断登录是否超时，超时跳转登录页面
   * 4、判读是否有权限访问页面，没有权限跳转登录页面
   */
  if(IgnoreAccess.includes(to.name)){
    next()
  }else{
    const token = store.state.user.token
    if(token){
      //校验权限
      if(IgnoreAccess.includes(to.name) || getAccess().includes(to.name)){
        next()
      }else{
        //访问未授权605
        next({ name: 'no_access' })
      }
    }else{
      //用户未登录603
      errorHandle(603)
      next({ name: 'login' })
    }
  }
})

router.afterEach(route => {
  ViewUI.LoadingBar.finish()
})

export default router
